package cn.cytong.nk0713.services;

import cn.cytong.nk0713.utils.nutz.CustomisedNutDao;
import cn.cytong.rpc.server.NutzRpcService;
import com.google.common.base.Preconditions;
import flexjson.JSONSerializer;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.entity.Record;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 终端信息
 */
public class TerminalService extends NutzRpcService {
    private Logger logger = LoggerFactory.getLogger(TerminalService.class);
    private CustomisedNutDao nutDao;

    /**
     * 获取景区终端信息
     * @param params    terminalNo  景区终端号
     * @return          terminal    终端信息
     *                  success     true or false
     */
    public String getTerminal(Map params) {
        Map result = new HashMap();
        String terminalNo = (String) params.get("terminalNo");
        try {
            Preconditions.checkArgument(StringUtils.isNotBlank(terminalNo), "终端号信息错误");
            Record terminal = nutDao.fetchTableRecord("terminal", "terminalNo = ?", terminalNo);
            Preconditions.checkNotNull(terminal, "终端号信息不存在");
            Record viewpoint = nutDao.fetchTableRecord("viewpoint", "id = ?", terminal.get("viewpoint_id"));
            terminal.put("viewpoint", viewpoint);
            result.put("terminal", terminal);
            result.put("success", true);
        } catch (Exception e) {
            logger.error("error in method TerminalService.getTermianl", e);
            result.put("success", false);
            result.put("msg", e.getMessage());
        }
        return new JSONSerializer().serialize(result);
    }

    /**
     * 保存终端信息
     * @param params    id          终端id
     *                  lastSignIn  最后签到时间
     *                  versionNo   版本号
     * @return          terminal    保存后的终端信息
     *                  success     true or false
     */
    public String saveTerminal(Map params) {
        Map result = new HashMap();
        Object id = params.get("id");
        Date lastSignIn = new Date();     //更新为当前时间
        String versionNo = (String) params.get("versionNo");
        try {
            Chain ch = Chain.make("lastSignIn", lastSignIn);
            if (StringUtils.isNotBlank(versionNo)) {
                ch.add("versionNo", versionNo);
            }
            Cnd cnd = Cnd.where("id", "=", id);
            dao.update("terminal", ch, cnd);
            Record terminal = dao.fetch("terminal", cnd);
            result.put("terminal", terminal);
            result.put("success", true);
        } catch (Exception e) {
            logger.error("error in method TerminalService.saveTerminal", e);
            result.put("success", false);
            result.put("msg", e.getMessage());
        }
        return new JSONSerializer().serialize(result);
    }
}
